package com.lfg.leetcode.leetcode0;

public class No25ReverseKGroup {

    public static ListNode reverseKGroup(ListNode head, int k) {

        ListNode ret = null;
        ListNode lastNode = null;
        while (head != null) {
            int i = k;
            ListNode firstNode = head;
            ListNode subList = null;

            ListNode checkNode = head;
            while (i > 0 && checkNode != null) {
                checkNode = checkNode.next;
                i--;
            }

            if (i != 0) {
                break;
            }
            i = k;
            while (i > 0 && head != null) {
                ListNode tmp = head.next;
                if (subList != null) {
                    head.next = subList;
                }
                subList = head;
                head = tmp;

                i--;
            }
            firstNode.next = head;
            if (ret == null) {
                ret = subList;
            }
            if (lastNode != null && i == 0) {
                lastNode.next = subList;
            }
            lastNode = firstNode;
        }
        if (ret == null) {
            ret = head;
        }
        return ret;
    }

    public static void main(String[] args) {
        ListNode l = reverseKGroup(ListNode.deserialize("[1,2,3,4,5,6,7,8,9,10,11,12]"), 5);
        while (l != null) {
            System.out.println(l.val);
            l = l.next;
        }
    }
}

